import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import Keys
from selenium.common.exceptions import SessionNotCreatedException
import subprocess
import socket
import psutil
import requests
import json
import time
import pyperclip
import edge_tts
import asyncio
import os
from mutagen.mp3 import MP3
import random

def random_list(my_list):
    random_element = random.choice(my_list)
    return random_element 

def kill(app):
    

    # 要结束的进程名称（不包括.exe）
    process_name = app

    # 查找进程
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            # 结束进程
            psutil.Process(proc.info['pid']).kill()
            print(f"Process {process_name} with PID {proc.info['pid']} has been terminated.")


#选择浏览器
def choose_browser(browser='Firefox'):
    if browser=='Firefox':
        
        #到这里下载最新火狐浏览器"https://www.mozilla.org/zh-CN/firefox/all/desktop-release/win64-msi/zh-CN/"
        #下面是firefox接管已打开网页的方法，调试时使用
        
        #"C:\Program Files\Mozilla Firefox\firefox.exe" -marionette -start-debugger-server 2828
        command = '"C:\\Program Files\\Mozilla Firefox\\firefox.exe"'
        command1=command+' -marionette -start-debugger-server 2828'
        if not test_port('127.0.0.1',2828):
            print('马上打开firefox机器调试模式')
            
            subprocess.Popen(command1)
        else:
            print('2828端口畅通，firefox已开启了机器调试模式')


        #firefox_services = Service(executable_path='C:/py/0929/geckodriver.exe',port=3000,service_args=['--marionette-port', '2828', '--connect-existing'])
        firefox_services = Service(executable_path=executable_path,port=3000,service_args=['--marionette-port', '2828', '--connect-existing'])
        #driver = webdriver.Firefox(service=firefox_services)
        #driver.close()
        try:
            return webdriver.Firefox(service=firefox_services)
        except SessionNotCreatedException as e:
            print("无法创建新的会话，可能是因为会话已经存在。错误信息：", e)
            print('正在尝试杀掉geckodriver.exe，重启firefox')
            kill('geckodriver.exe')
            return webdriver.Firefox(service=firefox_services)
        
    #driver = webdriver.Firefox(executable_path='C:\py\1006\geckodriver-0.35.0')
    if browser=='Chrome':
        # 创建 Options 选项对象
        opt = Options()
        opt.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'	# 指定 Chrome 浏览器的路径

        # 创建 Service 对象
        ser = Service()	
        ser.executable_path = r'C:\Program Files\Python312\chromedriver.exe'	# 指定 ChromeDriver 的路径
        chrome_location=r"C:\Program Files\Google\Chrome\Application\chrome.exe"
        '''
        
##        #open_chrome_command=chrome_location+' --remote-debugging-port=9222 --user-data-dir="c:\temp"'
##
##        open_chrome_command=chrome_location+' --remote-debugging-port=9222'
##        print(open_chrome_command)
##        command = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"'
##        command1=command+' --remote-debugging-port=9222'
##        print(command1)
##        print(command)
##
##        # 运行命令
##        #os.system(command1)
##        subprocess.Popen(command1)
        '''
        return webdriver.Chrome(options=opt)

#选中元素的xpath并点击
def click1(xpath,comments=''):
    if wait0(xpath):
        print(xpath,'click',comments)
        element = driver.find_element(By.XPATH, xpath)
        element.click()
        time.sleep(1)
#选中输入框的xpath并输入text    
def input1(xpath,text):
    if wait0(xpath):
        print(xpath,text)
        element = driver.find_element(By.XPATH, xpath)
        print('准备输入文本：',text)
        time.sleep(1)
        element.send_keys(text)
        time.sleep(1)

#选中输入框的xpath并输入text    
def input2(xpath,text):
    pyperclip.copy(text)
    if wait0(xpath):
        print(xpath,text)
        element = driver.find_element(By.XPATH, xpath)
        print('准备输入文本input2：',text)
        time.sleep(1)
        element.send_keys(Keys.CONTROL, 'v')
        #element.send_keys(text)
        time.sleep(1)

def input3(xpath):
    #pyperclip.copy(text)
    if wait0(xpath):
        print(xpath)
        element = driver.find_element(By.XPATH, xpath)
        #print('准备输入文本input2：',text)
        time.sleep(1)
        element.send_keys(Keys.CONTROL, 'v')
        #element.send_keys(text)
        time.sleep(1)
#等待元素出现
def wait0(xpath,comments='',max_attempts=3):
    print(xpath,comments)

    try:
        element = driver.find_element(By.XPATH, xpath)
        print(xpath,'已出现')
        return True
    except:
        print('waiting ......')
        if max_attempts > 0:
            time.sleep(5)
        
        
            wait0(xpath, comments, max_attempts - 1)
        else:
            print('已尝试n次，元素仍未出现。')
            driver.close()
            return False
        
#打开网页        
def open1(link,comments=''):
    print(comments,link)
    driver.get(link)
    time.sleep(2)

#获取xpath的文字
def get_text(xpath):
    #xpath='//*[@id="main_price"]/em'
    element = driver.find_element(By.XPATH, xpath)
    print('价格是',element.text)
    return element.text

#测试端口是否通
def test_port(ip, port):
    try:
        socket.create_connection((ip, port), timeout=1).close()
        print(ip,port,'端口通')
        return True
    except socket.error as e:
        print(f"Port {port} is not available.")
        return False

def get_latest_message(room_id):
    try:
        url='https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid='
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            # 可以添加更多需要的头部信息
        }
        print('*',url+room_id)
        
        response = requests.get(url+room_id, headers=headers)
        print('**',response)
        data =json.loads(response.text)
        #print(data)
        len0=len(data['data']['room'])
        text=data['data']['room'][len0-1]['text']
        print(len0,text)
        if text is None:
            text='你好呀'

        return text
    except:
        time.sleep(3)
        get_latest_message(room_id)

def hailuo_search_and_play_latest(message):
    #//*[@id="chat-input-box"]
    #//*[@id="chat-input"]
    input_xpath='//*[@id="chat-input"]'
    #element.send_keys(Keys.CONTROL, 'v')
    input1(input_xpath,message)
    input1(input_xpath,Keys.ENTER)
    #click1('/html/body/div/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[4]/div/div[1]/div[1]/div/div[2]/div/div[17]/div/div/div/div/div/div[2]/div[1]/div/div[2]/div[1]/button[1]/span[2]')
    elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
    len0=len(elements)
    mode=0
    for _ in range(20):
        if mode ==0:
            time.sleep(2)
            elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
            len1=len(elements)
            
            if len1==len0:
                print('未完成，请等待')
            
            else:
                mode=1
                break
    
    element = elements[-1]
    element.click()

def hailuo_search_and_play_latest2():
    #//*[@id="chat-input-box"]
    #//*[@id="chat-input"]
    input_xpath='//*[@id="chat-input"]'
    element_hailuo = driver.find_element(By.XPATH, '//*[@id="chat-input"]')
    element_hailuo.click()  # 点击目标元素
    element_hailuo.clear()  # 清空目标元素中的内容
    element_hailuo.send_keys(pyperclip.paste())
    time.sleep(1)
    element_hailuo.send_keys(Keys.ENTER)

##    #click1('/html/body/div/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[4]/div/div[1]/div[1]/div/div[2]/div/div[17]/div/div/div/div/div/div[2]/div[1]/div/div[2]/div[1]/button[1]/span[2]')
    elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
    len0=len(elements)
    mode=0
    for _ in range(20):
        if mode ==0:
            time.sleep(2)
            elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
            len1=len(elements)
            
            if len1==len0:
                print('未完成，请等待')
            
            else:
                mode=1
                break
    
    element = elements[-1]
    element.click()

def hailuo_search_and_play_latest(message):
    #//*[@id="chat-input-box"]
    #//*[@id="chat-input"]
    input_xpath='//*[@id="chat-input"]'
    #element.send_keys(Keys.CONTROL, 'v')
    input1(input_xpath,message)
    input1(input_xpath,Keys.ENTER)
    #click1('/html/body/div/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[4]/div/div[1]/div[1]/div/div[2]/div/div[17]/div/div/div/div/div/div[2]/div[1]/div/div[2]/div[1]/button[1]/span[2]')
    elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
    len0=len(elements)
    mode=0
    for _ in range(20):
        if mode ==0:
            time.sleep(2)
            elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
            len1=len(elements)
            
            if len1==len0:
                print('未完成，请等待')
            
            else:
                mode=1
                break
    
    element = elements[-1]
    element.click()

def kimi_search_and_play_latest(message):
    #//*[@id="chat-input-box"]
    #//*[@id="chat-input"]
    input_xpath='/html/body/div/div/div[1]/div[2]/div[1]/div/div/div/div/div[1]/div[4]/div/div[2]/div/div[1]/div/div/div[1]/div[1]'
    
    input2(input_xpath,message)
    time.sleep(1)
    input1(input_xpath,Keys.ENTER)
    time.sleep(30)
    #/symbol/path[1]
    kimi_elements = driver.find_elements(By.XPATH, "//span[text()='复制']")
    #//div[contains(@class, 'cnt') and contains(@class, 'f-brk')]
    print(len(kimi_elements))
    #elements=driver.find_elements(By.CSS_SELECTOR, ".MuiTypography-root.MuiTypography-body1.label___TPWYH.css-17cnyc1")
    #<span class="MuiTypography-root MuiTypography-body1 label___TPWYH css-17cnyc1">复制</span>
    #print(len(elements))
    #print(elements[-1])
    
##    len0=len(elements)
##    mode=0
##    for _ in range(20):
##        if mode ==0:
##            time.sleep(2)
##            elements=driver.find_elements(By.CSS_SELECTOR, ".MuiTouchRipple-root.css-w0pj6f")
##            len1=len(elements)
##            
##            if len1==len0:
##                print('未完成，请等待')
##            
##            else:
##                mode=1
##                break
##    
    kimi_element = kimi_elements[-1]
    mark_red(kimi_element)
    
    kimi_element.click()
    print('*********kimi copy end******')

def mark_red(element):
        # 获取元素的引用
    element_ref = driver.execute_script("return arguments[0]", element)

    # 使用JavaScript来高亮显示元素
    driver.execute_script("""
        var element = arguments[0];
        element.style.border = '3px solid red'; // 设置边框为红色高亮显示
    """, element_ref)

#async def run_tts(text: str, output: str, voice: str ='zh-CN-XiaoxiaoNeural') -> None:
async def run_tts(text: str, output: str, voice: str ='zh-CN-XiaoxiaoNeural') -> None:
    communicate = edge_tts.Communicate(text, voice)
    print(dir(communicate))
    #communicate.say()
    await communicate.save(output)


def read(text):
    asyncio.run(run_tts(text, 'a.mp3'))
    os.system('start a.mp3 ')
def read1(message,voice='zh-CN-XiaoxiaoNeural'):
    
##zh-CN-XiaoshuangNeural（女性、儿童）
##zh-CN-XiaoxiaoDialectsNeural（女）
##zh-CN-XiaoxiaoMultilingualNeural4（女）
##zh-CN-XiaoyanNeural（女）
##zh-CN-XiaoyouNeural（女性、儿童）
##zh-CN-XiaoyuMultilingualNeural4（女）
##zh-CN-XiaozhenNeural（女）
##zh-CN-YunfengNeural（男）
##zh-CN-YunhaoNeural（男）
##zh-CN-YunjieNeural（男）
##zh-CN-YunxiaNeural（男）
##zh-CN-YunyeNeural（男）
##zh-CN-YunyiMultilingualNeural4（男）
##zh-CN-YunzeNeural（男）
##zh-CN-YunfanMultilingualNeural1,4（男）
##zh-CN-YunxiaoMultilingualNeural]
    message=message.replace('\n','').replace('\r','')
    #print('edge-playback --rate=-20% --text "{}"  --voice=zh-CN-XiaoxiaoNeural'.format(message))
    #zh-TW-HsiaoChenNeural   zh-CN-XiaoxiaoNeural
    #https://learn.microsoft.com/zh-cn/azure/ai-services/speech-service/language-support?tabs=tts
    #os.system('edge-playback --rate=-20% --pitch=-5Hz --text "{}"  --voice=zh-TW-HsiaoChenNeural '.format(message))
    #command='edge-tts --rate=-25%  --write-media hello.mp3 --voice={} --text "{}" && timeout /t 10'.format(voice,message)
    #command='edge-tts --rate=-25%  --write-media hello.mp3 --voice={} --text "{}" && start hello.mp3'.format(voice,message)
    command='edge-playback --rate=-25% --text "{}"  --voice=zh-CN-XiaoxiaoNeural'.format(message)
    #print(command)
    os.system(command)
    #time1=int(MP3('hello.mp3').info.length)+10
    #print(time1)
    ##time.sleep(int(time1))
    #time.sleep(10)
    
    #print(MP3('hello.mp3').info.length)
    #os.system('hello.mp3')
    #time.sleep(int(MP3('hello.mp3').info.length))
    #kill('wmplayer.exe')
    #os.system('echo '' > hello.mp3')
    #time.sleep(3)

def seprate_texts(text,chunk_size = 1200):

      # 每份的大小

    # 计算需要多少个完整的chunk以及是否有剩余
    num_full_chunks = len(text) // chunk_size
    remaining_text = len(text) % chunk_size

    # 切割文本
    chunks = []
    for i in range(num_full_chunks):
        start = i * chunk_size
        end = start + chunk_size
        chunks.append(text[start:end])

    # 如果有剩余的文本，添加到最后的chunk中
    if remaining_text > 0:
        chunks.append(text[-num_full_chunks*chunk_size:])
    return chunks

        
if __name__ == "__main__":
    print('start')
    #下载firfox的geckodriver驱动
    #https://github.com/mozilla/geckodriver/releases
    #名字叫geckodriver-v0.35.0-win32.zip
    #解压到自己计算机的制定位置,注意位置是双斜杠，改成自己的geckodriver.exe路径
    executable_path='./geckodriver.exe'
    text='''
黄河因上游连续的积雨涨成深黄，细看就是一川泥流。人在岸边，满鼻子激荡着巨大的腥味。燕子也飞得更高，像是在躲避这种狂野的味道。不能驯服的河水，被强大的石岸夹在高楼大厦下面，不安又无奈，只能顺着未知前进，奔向更远的未知。我从既有的经验里知道它们的前景，所以自然不为它们担心前行的陌生会怎样伤透它们的心肠，可是也知道它们此去无坦途，千折百回地激情澎湃，却未必能够获得初心，启动发轫青藏高原时的一湾安静与稳健。我在它的上游贴近它温柔安闲的高贵，在牦牛竖着尾巴奔跑的青草地，畅想过这种高贵怎样的冷艳，怎样的目空一切，却总是缺乏激情四射、热烈拥抱未来的雄心。直到有一天抵达两大高原相碰撞的壶口，一渠大河突然跌落，将上游的平静粉碎，在犹如万马奔腾的怒吼中，收集起破碎在空气里的咆哮与嘶吼，呼啸着冲出峡谷，我突然明白它们有了新气象、新生命！然而，无论如何，青藏高原始发地的草地清溪，经历黄土拥抱，变成刚强坚定的大河，直奔万里之外的浩瀚大海，却再也不会回首自怜。
'''
    
    #read1(text)
    
    #time.sleep()
    print('end***')
    
    #选择浏览器并打开，默认是火狐
    driver = choose_browser()
##
##    # 使用JavaScript打开第二个网页
##
##    
##    #open('https://music.163.com/#/song?id=1950343972')
##    #海螺ai
##    kimi_link='https://kimi.moonshot.cn/chat/cs2k2vqlve9jd07gq1u0'
##    #link='https://www.baidu.com'
    
    open1('https://www.duanmeiwen.com/gushi/aiqing/22895.html')
    voices=['zh-CN-XiaoxiaoNeural','zh-CN-XiaoyiNeural','zh-CN-YunjianNeural','zh-CN-YunxiNeural','Name: zh-CN-YunxiaNeural','zh-CN-YunyangNeural']
    text_elements = driver.find_elements(By.TAG_NAME, 'p')
    text_content = '\n'.join([element.text for element in text_elements])

    # 打印提取的文本内容
    print(text_content)
    for item in seprate_texts(text_content):
        try:
##        
##                #read1(item,voice=voice)
            read1(item)
        except:
                pass
        
##    for i in range(200):
##        xpath='//*[@id="htmlContent"]'
##        #voice=random_list(voices)
##        x=driver.find_element(By.XPATH,xpath)
##        for item in seprate_texts(x.text):
##            try:
##        
##                #read1(item,voice=voice)
##                read1(item)
##            except:
##                pass
##        next_link = driver.find_element(By.LINK_TEXT, "下一篇")
##        next_link.click()
##        time.sleep(5)
##    
    
##    xpath='/html/body/div[3]/div[1]/div/div/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[1]/div'
##    elements = driver.find_elements(By.XPATH, '/html/body/div[3]/div[1]/div/div/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[1]/div')
##    /html/body/div[3]/div[1]/div/div/div[2]/div/div[2]/div[2]/div[1]/div[2]/div[1]/div
##    #\35 6757414141728472504345 > div:nth-child(2) > div:nth-child(1) > div:nth-child(1)
##    html body#auto-id-W1IKZp0y08od0liu.auto-1728472504349-parent div.g-bd4.f-cb div.g-mn4 div.g-mn4c div.g-wrap6 div#comment-box.n-cmt div#auto-id-smf132Cla6Qh4C3M div.m-cmmt div#auto-id-L4KZko6OOZLX7HI6.cmmts.j-flag div#56757414141728472504345.itm div.cntwrap div div.cnt.f-brk
##    print(elements)
##    
##    for i in range(500):
##
##        #kimi_search_and_play_latest('你能写一份女性向的睡前哄睡吗？类似男朋友的轻声私语，短文本，200字以内即可')
##        kimi_search_and_play_latest('再来一个不一样的，短文本，200字以内即可')
##        content = pyperclip.paste().replace('#','').replace('*',"")
##        print(content)
##        read1(content)
##        time.sleep(45)
##
##    print('end')
